package com.d.common.exception;

import com.d.common.utils.RT;
import org.springframework.util.StringUtils;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.ConstraintViolationException;


/**
 * Validator 自定义异常
 * 注解参数效验 错误信息捕捉异常，按自定义格式返回错误信息
 */
@ControllerAdvice
public class ValidatorException {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public RT handleBindException(MethodArgumentNotValidException ex) {
        FieldError fieldError = ex.getBindingResult().getFieldError();
        String message ="参数异常";
        if(fieldError !=null){
            message =fieldError.getDefaultMessage();
        }
        return RT.error(400, message);
    }

    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseBody
    public RT handleBindException(ConstraintViolationException ex) {
        String message = StringUtils.isEmpty(ex.getLocalizedMessage()) ? "参数异常":ex.getLocalizedMessage();
        return RT.error(400, message);
    }

}
